<?php
namespace Components\Account\User\Wallet;

use Components\Account\User\Adapter;

class Validation extends \Phalcon\Validation {
  public function execute($data) {
    $validationMessages = $this -> validate($data);
    if($validationMessages -> valid()) {
      return ['code'=>-1,'message'=>$validationMessages[0]->getMessage()];
    }

    $resData = [];
    foreach($this -> getValidators() as $v) {
      if(isset($data[$v[0]]) && !empty($data[$v[0]])) {
        $filterFunName = 'check' . ucfirst($v[0]);
        if(strstr($filterFunName, 'password')) {
          continue;
        }

        if(!method_exists(Adapter::getWalletFilterInstance(), $filterFunName)) { return ['code'=>-1,'message'=>'请联系开发人员:'.get_class(Adapter::getWalletFilterInstance()) . '->' . $filterFunName . '不存在!']; }
        $resData[$v[0]] = Adapter::getWalletFilterInstance() -> $filterFunName($data[$v[0]]);
      }
    }

    return ['code'=>0,'data'=>$resData];
  }

  public function addFields() {
    return $this -> rules('fields',[
      new \Phalcon\Validation\Validator\InclusionIn([
        'message' => '选择的类型有误',
        'domain' => [1, 2, 3, 4, 5]
      ])
    ]);
  }

  public function addAmount() {
    return $this -> rules('amount',[
      new \Phalcon\Validation\Validator\PresenceOf(),
      new \Phalcon\Validation\Validator\Callback([
        'message' => '数量不能等于0',
        'callback' => function($data) {
          if(!isset($data['amount']) || empty($data['amount'])) {
            return false;
          }

          if($data['amount'] == 0) {
            return false;
          }

          return true;
        }
      ])
    ]);
  }

  public function addSafePassword($id) {
    return $this -> rules('safe_password',[
      new \Phalcon\Validation\Validator\Callback([
        'message' => '安全密码错误',
        'callback' => function($data) use ($id) {
          if(!isset($data['safe_password']) || empty($data['safe_password'])) {
            return false;
          }

          $res = Adapter::getServiceInstance() -> findFirst(['user_id = ' . $id]);
          if($res['code'] != 0) {
            return false;
          }

          return Adapter::getDI('security') -> checkHash($data['safe_password'], $res['model'] -> safe_password);
        }
      ])
    ]);
  }
}
